const UserModel = require('../service/user');
const {sucResult, errResult } = require('../middlewares/resResult');
const sha1 = require('sha1');
const jwt = require('jsonwebtoken');
class UserController {

  /**
   * 注册
   * @param ctx
   * @returns {Promise<void>}
   */
  static async signin (ctx) {
    // 接收客服端
    let req = {
      name: ctx.request.body.name,
      password: sha1(ctx.request.body.password),
      token: jwt.sign({ hello: ctx.request.body.user }, 'xiangxu', { expiresIn: 24 * 60 * 60 * 1 })
    };
    if (req.name &&
      req.password
    ) {

      let created = await UserModel.createUser(req);
      if (created) {
        ctx.body = sucResult(created, '注册成功');
      } else {
        ctx.body = errResult('账号已存在', created);
      }
    } else {
      ctx.body = errResult('参数不齐全');
    }
  }

  /**
   * 登录
   * @param ctx
   * @returns {Promise<void>}
   */
  static async login (ctx) {
    let req = {
      name: ctx.request.body.name,
      password: sha1(ctx.request.body.password)
    };
    try {
      let data = await UserModel.getUser(req);
      if (data) {
        data.token = jwt.sign({name: data.name}, 'xiangxu', { expiresIn: '2h' });
        data.password = '*****';
        ctx.body = sucResult(data, '登录成功');
      } else {
        ctx.body = errResult('用户名或密码错误');
      }

    } catch (err) {
      errResult('登录失败');
    }
  }

  /**
   * 删除
   * @param ctx
   * @returns {Promise<void>}
   */
  static async deleteUser (ctx) {
    let id = ctx.query.id;
    let data = await UserModel.deleteUser(id);
    if (data) {
      ctx.body = sucResult({}, '删除成功');
    } else {
      ctx.body = errResult('删除失败，用户不存在');
    }
  }

  /**
   * 查询用户
   * @param ctx
   * @returns {Promise<void>}
   */
  static async getUserList (ctx) {
    let req = {
      limit: parseInt(ctx.query.limit),
      page: ctx.query.page
    };
    try {
      let data = await UserModel.getUserList(req);
      ctx.body = sucResult(data);
    } catch (err) {
      ctx.body = errResult('查询失败');
    }
  }

  /**
   * 查询用户--按角色查询
   * @param ctx
   * @returns {Promise<void>}
   */
  static async getUserByRole (ctx) {
    let req = {
      limit: parseInt(ctx.query.limit),
      page: ctx.query.page,
      roleId: ctx.query.roleId
    };
    try {
      let data = await UserModel.getUserByRole(req);
      ctx.body = sucResult(data);
    } catch (err) {
      ctx.body = errResult('查询失败');
    }
  }
}

module.exports = UserController;
